﻿var zombies = zombies || {};

zombies.ListAdvertise = function () {
    var self = this;
    self.Advertises = ko.observableArray();
    self.cbbCategories = ko.observableArray();
    self.SearchString = ko.observable("");
    self.CurrentPage = ko.observable(1);
    self.IsPrevious = ko.observable(false);
    self.IsNext = ko.observable(false);
    self.Loaded = ko.observable(false);

    self.AdvId = ko.observable();
    self.Title = ko.observable();
    self.ProductName = ko.observable();
    self.Description = ko.observable();
    self.ShortDes = ko.observable();
    self.Views = ko.observable();
    self.Rate = ko.observable();
    self.Likes = ko.observable();
    self.DateCreated = ko.observable();
    self.CompanyName = ko.observable();
    self.Name = ko.observable();
    self.PreviewImg = ko.observable();
    self.Categories = ko.observableArray();
    self.Medias = ko.observableArray();
    self.Comments = ko.observableArray();

    self.IsImage = ko.computed(function () {
        if (self.Name() === 'Images') {
            return true;
        }
        return false;
    });
    self.IsFlash = ko.computed(function () {
        if (self.Name() === 'Flash') {
            return true;
        }
        return false;
    });
    self.IsVideo = ko.computed(function () {
        if (self.Name() === 'Video') {
            return true;
        }
        return false;
    });

    self.doView = function (item) {
        self.AdvId(item.AdvId);
        self.Title(item.Title);
        self.ProductName(item.ProductName);
        self.Description(item.Description);
        CKEDITOR.instances['ckeditor-des'].setData(item.Description);
        self.ShortDes(item.ShortDes);
        self.Views(item.Views);
        self.Rate(item.Rate);
        self.Likes(item.Likes);
        self.DateCreated(moment(item.DateCreated).format("dddd, MMMM D, YYYY"));
        self.CompanyName(item.CompanyName);
        self.Name(item.Name);
        self.PreviewImg(item.PreviewImg);
        self.Categories.removeAll();
        self.Medias.removeAll();
        self.Comments.removeAll();
        $.ajax({
            url: '/api/AdminAdv/GetCategpriesByAdv/' + item.AdvId,
            type: 'GET',
            contentType: "application/json; charset=utf-8",
            dataType: "json"
        }).done(function (items) {
            $.each(items, function (idx, item) {
                self.Categories.push(new zombies.Category(item));
            });
        }).error(function () {
            toastr.error('Lỗi');
        })
        $.ajax({
            url: '/api/AdminAdv/GetMediaByAdv/' + item.AdvId,
            type: 'GET',
            contentType: "application/json; charset=utf-8",
            dataType: "json"
        }).done(function (items) {
            $.each(items, function (idx, item) {
                self.Medias.push(new zombies.Media(item));
            });
        }).error(function () {
            toastr.error('Lỗi');
        })
        $.ajax({
            url: '/api/AdminAdv/GetCommentsByAdv/' + item.AdvId,
            type: 'GET',
            contentType: "application/json; charset=utf-8",
            dataType: "json"
        }).done(function (items) {
            $.each(items, function (idx, item) {
                self.Comments.push(new zombies.Comment(item));
            });
        }).error(function () {
            toastr.error('Lỗi');
        })
    };

    self.SendMsg = function () {
        self.CurrentPage(1);
        load(self.CurrentPage(), self.SearchString());
        $.replaceUrl(self.CurrentPage(), self.SearchString());

    };

    self.EnterSendMsg = function (data, event) {
        try {
            if (event.which === 13) {
                self.CurrentPage(1);
                load(self.CurrentPage(), self.SearchString());
                $.replaceUrl(self.CurrentPage(), self.SearchString());
                return false;
            }
            return true;
        }
        catch (e)
        { }
    }

    self.doEditAdv = function (formElement) {
        var advertise = ko.utils.arrayFirst(self.Advertises(), function (item) {
            return item.AdvId === self.AdvId();
        });

        var dataToEdit = {
            AdvId: self.AdvId,
            Title: self.Title,
            ProductName: self.ProductName,
            Description: CKEDITOR.instances['ckeditor-des'].getData(),
            ShortDes: self.ShortDes
        };

        if ($(formElement).valid()) {
            $.ajax({
                type: "PUT",
                url: "/api/AdminAdv/PutAdvertise",
                data: ko.toJSON(dataToEdit), //Convert the Observable Data into JSON
                contentType: "application/json",
                dataType: 'json'
            }).done(function () {
                toastr.success('Edit Advertise Successfully !');
                self.Advertises.replace(advertise, {
                    AdvId: self.AdvId(),
                    Title: self.Title(),
                    ProductName: self.ProductName(),
                    ShortDes: self.ShortDes(),
                    Description: CKEDITOR.instances['ckeditor-des'].getData(),
                    Views: self.Views(),
                    Rate: self.Rate(),
                    Likes: self.Likes(),
                    DateCreated: self.DateCreated(),
                    CompanyName: self.CompanyName(),
                    Categories: self.Categories(),
                    Medias: self.Medias(),
                    Name: self.Name(),
                    PreviewImg: self.PreviewImg()
                });
                $('#editad-div').removeClass('active in');
                $('#listads-div').addClass('active in');
            }).fail(function () {
                toastr.error('Edit Advertise Failed !');
            });
        }
    };

    self.doDelete = function (adv) {
        var advDel = ko.utils.arrayFirst(self.Advertises(), function (item) {
            return item.AdvId === adv.AdvId;
        });
        $('#myAdvertise').modal('hide');
        $.confirm({
            text: "Bạn Có Chắc Chắc Xóa Quảng Cáo <strong style='color: red'>" + adv.Title + "</strong> Không?</br>Thao Tác Này Không Thể Khôi Phục",
            title: "<strong>Xác Nhận Xóa</strong>",
            confirm: function (button) {
                $.ajax({
                    type: "DELETE",
                    url: "/api/AdminAdv/DeleteAdvertise/" + adv.AdvId,
                    success: function (data) {
                        self.Advertises.remove(advDel);
                        toastr.success("Xóa Thành Công");
                        if (self.CurrentPage() > 1 && self.Advertises().length == 0) {
                            self.doPrevious();
                        }
                    },
                    error: function (request) {
                        toastr.error("Xóa Thất Bại");
                    }
                });
            },
            confirmButton: "Tiếp Tục Xóa",
            cancelButton: "Thoát"
        });
    };

    self.doNext = function () {
        if (self.IsNext()) {
            var page = self.CurrentPage();
            page++;
            self.CurrentPage(page);
            load(page, self.SearchString);
            if (page == 1) {
                self.IsPrevious(false)
            } else {
                self.IsPrevious(true);
            }
            $.replaceUrl(page, self.SearchString());
            App.scrollTo($('#listads-div'), -50);
        }
    };

    self.doPrevious = function () {
        if (self.IsPrevious()) {
            var page = self.CurrentPage() - 1;
            self.CurrentPage(page);
            load(page, self.SearchString);
            if (page == 1) {
                self.IsPrevious(false)
            } else {
                self.IsPrevious(true);
            }
            $.replaceUrl(page, self.SearchString());
            App.scrollTo($('#listads-div'), -50);
        }
    };

    self.doEditComment = function (item, event) {
        var comment = ko.utils.arrayFirst(self.Comments(), function (i) {
            return i.CommentId === item.CommentId;
        });
        var key = $(event.target).attr('href');
        var hide = item.Hide;
        var spam = item.Spam;
        if (key === '#hide') {
            hide = !item.Hide;
        } else {
            spam = !item.Spam;
        }
        var dataToEdit = {
            CommentId: item.CommentId,
            Hide: hide,
            Spam: spam
        };

        $.ajax({
            type: "PUT",
            url: "/api/AdminAdv/PutComment",
            data: ko.toJSON(dataToEdit), //Convert the Observable Data into JSON
            contentType: "application/json",
            dataType: 'json'
        }).done(function () {
            toastr.success('Edit Advertise Successfully !');
            self.Comments.replace(comment, {
                CommentId: item.CommentId,
                Name: item.Name,
                Content: item.Content,
                DateComment: moment(item.DateComment).format("dddd, MMMM D, YYYY"),
                Type: item.Type,
                Id: item.Id,
                ParentId: item.ParentId,
                Spam: spam,
                Hide: hide,
                Avatar: item.Avatar
            });
        }).fail(function () {
            toastr.error('Edit Advertise Failed !');
        });
    }
}
var loadAllCategory = function () {
    $.ajax({
        url: '/api/AdminCategory/GetAllCategories',
        type: 'GET',
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    }).done(function (items) {
        viewModel.cbbCategories.push('');
        $.each(items, function (idx, item) {
            viewModel.cbbCategories.push(new zombies.Category(item));
        });
    }).error(function () {
        toastr.error('error load categories');
    })
};

var load = function (id, searchString) {
    viewModel.Loaded(true);
    viewModel.Advertises.removeAll();
    $.ajax({
        url: '/api/AdminAdv/GetAdvertises/' + id,
        type: 'GET',
        data: { value: searchString },
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    }).done(function (items) {
        if (items.length === 11) {
            items.pop();
            viewModel.IsNext(true);
        } else {
            viewModel.IsNext(false);
        }
        $.each(items, function (idx, item) {
            viewModel.Advertises.push(new zombies.Advertise(item));
        });
        viewModel.Loaded(false);
    }).error(function () {
        toastr.error('error');
    })
};

var viewModel;
$(document).ready(function () {
    viewModel = new zombies.ListAdvertise();

    ko.applyBindings(viewModel, document.getElementById("admin_content"));

    var pageUrl = $.getUrlVars("page");
    var searchStringUrl = $.getUrlVars("searchString");
    if (typeof pageUrl === 'undefined' || !isFinite(String(pageUrl))) {
        viewModel.CurrentPage(1);
    } else {
        viewModel.CurrentPage(pageUrl);
    }
    if (typeof searchStringUrl === 'undefined') {
        viewModel.SearchString("");
    } else {
        viewModel.SearchString(searchStringUrl);
    }
    if (pageUrl > 1) viewModel.IsPrevious(true);
    load(viewModel.CurrentPage(), viewModel.SearchString());
    loadAllCategory();
});